package com.pig4cloud.pig.ads.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.entity.AdRoleUser;
import com.dy.yunying.api.feign.RemoteAdRoleUserService;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.service.AdAccountService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TtCustomAudienceService;
import com.pig4cloud.pig.api.dto.AllCustomAudienceDTO;
import com.pig4cloud.pig.api.dto.TtCustomAudiencesDTO;
import com.pig4cloud.pig.api.entity.AdAccount;
import com.pig4cloud.pig.api.entity.AllCustomAudience;
import com.pig4cloud.pig.api.entity.TtCustomAudience;
import com.pig4cloud.pig.api.entity.TtCustomAudienceDTO;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@RequestMapping("/ttCustomAudience")
@Api(value = "ttCustomAudience", tags = "头条人群包模块")
//@Inner(value = false)
public class TtCustomAudienceController {

	private final TtCustomAudienceService ttCustomAudienceService;

	private final AdvService advService;
	private final AdAccountService adAccountService;
	private final RemoteAdRoleUserService remoteAdRoleUserService;



	/**
	 * @上传人群包和创建数据源   整体接口
	 * @param file
	 * @param ttCustomAudiencesDTO
	 * @return
	 */
	@SysLog("上传人群包和创建数据源")
	@RequestMapping("/create")
	public R create(MultipartFile[] file, @Valid TtCustomAudiencesDTO ttCustomAudiencesDTO) {
		if (ttCustomAudiencesDTO == null) {
			return R.failed("未获取到提交信息！");
		}
		if(file == null || file.length == 0) {
			return R.failed("未获取到文件信息！");
		}
		LambdaQueryWrapper<TtCustomAudience> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(TtCustomAudience::getMediaType,PlatformTypeEnum.TT.getValue()));
		query.and(wrapper -> wrapper.eq(TtCustomAudience::getName, ttCustomAudiencesDTO.getData_source_name()));
		List<TtCustomAudience> list = ttCustomAudienceService.list(query);
		if (!CollectionUtils.isEmpty(list)) {
			return R.failed("人群包名称已存在!");
		}
		return ttCustomAudienceService.create(file, ttCustomAudiencesDTO);
	}

	/**
	 * 查询 是按角色维度
	 * @param mediaType
	 * @return
	 */
	@GetMapping("getAccountListByMediaType")
	public R getAccountListByMediaType(@RequestParam(required = false) Integer mediaType,
									   @RequestParam(required = false) String advertiserId){
		return R.ok(advService.getAccountList(mediaType,advertiserId));
	}


	/**
	 * 查询 是按角色维度
	 * 上传 是按投放人
	 * @param audienceDTO
	 * @return
	 */
	@SysLog("媒体人群包列表")
	@PostMapping("list")
	public R getAudienceList(@RequestBody AllCustomAudienceDTO audienceDTO) {
		//查询统计信息时查询日期必填
		if (audienceDTO.getTarget() != 1
				&& (StringUtils.isBlank(audienceDTO.getStartDate())
				|| StringUtils.isBlank(audienceDTO.getEndDate()))) {
			return R.failed("请输入查询日期");
		} else if (audienceDTO.getTarget() == 1) {
			//查询人群包不需要带时间
			audienceDTO.setStartDate("");
			audienceDTO.setEndDate("");
		}
		if (audienceDTO.getMediaType() != null && audienceDTO.getMediaType() == 0) {
			audienceDTO.setMediaType(null);
		}
		List<String> adList = Lists.newArrayList();
		//当前登录人所关联角色对应的投放人集合
		List<String> throwUserList = advService.getThrowUserList();
		// throwUserList == null 表示 为管理员或关联的角色关联了全部投放人
		if (!CollectionUtils.isEmpty(throwUserList)) {
			adList = adAccountService.list(Wrappers.<AdAccount>query().lambda()
					.and(wrapper -> wrapper.in(AdAccount::getThrowUser, throwUserList)))
					.stream().map(AdAccount::getAdvertiserId).collect(Collectors.toList());
		}
		if (!CollectionUtils.isEmpty(audienceDTO.getAdvertiserIds())) {
			adList.clear();
			adList.addAll(audienceDTO.getAdvertiserIds());
		}
		audienceDTO.setAdList(adList);
		audienceDTO.setThrowUserList(throwUserList);
		IPage<AllCustomAudience> pageResult = ttCustomAudienceService.getAudienceList(audienceDTO);
		return R.ok(pageResult);
	}

	@SysLog("删除人群包")
	@GetMapping("delete")
	public R getAudienceList (@RequestParam Long id) {
		if (id == null) {
			return R.failed("缺少必填参数");
		}
		return ttCustomAudienceService.deleteAudience(id);
	}


	/**
	 * 分页查询头条人群包信息
	 * @param page 分页对象
	 * @return 分页对象
	 */
	@SysLog("分页查询头条人群包信息")
	@GetMapping("/page")
	public R getAdverPage(Page page, TtCustomAudienceDTO tcaDto) {

		Integer id = SecurityUtils.getUser().getId();

		List<String> adList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if(adList == null || adList.size() == 0) {
			return R.ok(new Page());
		}

		LambdaQueryWrapper<TtCustomAudience> query = new LambdaQueryWrapper<>();

		query.and(wrapper -> wrapper.in(TtCustomAudience::getAccountId, adList));
		//人群ID/名称
		query.and(StringUtils.isNotBlank(tcaDto.getCustomAudienceId()), wrapper -> wrapper.eq(TtCustomAudience::getCustomAudienceId, tcaDto.getCustomAudienceId())
                .or().eq(StringUtils.isNotBlank(tcaDto.getCustomAudienceId()), TtCustomAudience::getName, tcaDto.getCustomAudienceId()));
        //广告账号
		query.and(tcaDto.getAdvertiserIds() != null && tcaDto.getAdvertiserIds().length > 0, wrapper -> wrapper.in(TtCustomAudience::getAccountId, Arrays.asList(tcaDto.getAdvertiserIds())));
        //类别
		query.and(StringUtils.isNotBlank(tcaDto.getSource()), wrapper -> wrapper.eq(TtCustomAudience::getSource, tcaDto.getSource()));
        //创建时间
		query.apply(StringUtils.isNotBlank(tcaDto.getSdate()),
                "date_format (create_time,'%Y-%m-%d') >= date_format('" + tcaDto.getSdate() + "','%Y-%m-%d')");
		query.apply(StringUtils.isNotBlank(tcaDto.getEdate()),
                "date_format (create_time,'%Y-%m-%d') <= date_format('" + tcaDto.getEdate() + "','%Y-%m-%d')");
        //状态(可用/不可用)
		query.and(StringUtils.isNotBlank(tcaDto.getDeliveryStatus()) && "CUSTOM_AUDIENCE_DELIVERY_STATUS_AVAILABLE".equals(tcaDto.getDeliveryStatus()), wrapper -> wrapper.eq(TtCustomAudience::getDeliveryStatus, tcaDto.getDeliveryStatus()));
		query.and(StringUtils.isNotBlank(tcaDto.getDeliveryStatus()) && !"CUSTOM_AUDIENCE_DELIVERY_STATUS_AVAILABLE".equals(tcaDto.getDeliveryStatus()), wrapper -> wrapper.ne(TtCustomAudience::getDeliveryStatus, "CUSTOM_AUDIENCE_DELIVERY_STATUS_AVAILABLE"));
        //覆盖数量 1： 10w-100w   2：100w-500w   3:500w以上
        //lt：小于 le：小于等于 eq：等于 ne：不等于 ge：大于等于 gt：大于
		query.and(tcaDto.getCoverNumType() != null && tcaDto.getCoverNumType() == 1, wrapper -> wrapper.ge(TtCustomAudience::getCoverNum, 100000).lt(TtCustomAudience::getCoverNum, 1000000));
		query.and(tcaDto.getCoverNumType() != null && tcaDto.getCoverNumType() == 2, wrapper -> wrapper.ge(TtCustomAudience::getCoverNum, 1000000).lt(TtCustomAudience::getCoverNum, 5000000));
		query.and(tcaDto.getCoverNumType() != null && tcaDto.getCoverNumType() == 3, wrapper -> wrapper.ge(TtCustomAudience::getCoverNum, 5000000));
        //根据创建时间倒序
		query.orderByDesc(TtCustomAudience::getTtCreateTime);

		return R.ok(ttCustomAudienceService.page(page, query));
	}



}
